import { create } from '@prequest/miniprogram'
import Lock from '@prequest/lock'
import { useAppStore } from '@/stores'
import { encrypt } from '@/utils/tool'
import serverConf from '@/config'

const http = create(uni.request, {
  baseURL: serverConf.api,
  // header: {
  //   'Content-Type': 'application/x-www-form-urlencoded',
  // },
})

export const lock = new Lock({
  getValue () {
    return Promise.resolve(uni.getStorageSync('im-token'))
  },
  setValue (token) {
    uni.setStorageSync('im-token', token)
  },
  clearValue () {
    uni.removeStorageSync('im-token')
  },
})

interface loginData {
  code: number,
  data: {
    token: string
  }
}

export async function login () {
  const appStore = useAppStore()
  const appId = appStore.appInfo.appId
  let token = ''

  // #ifdef MP-WEIXIN
  const { code } = await wx.login()
  const key = { code, appId }
  const dto = encrypt(JSON.stringify(key))
  // 登陆获取token接口
  const { code: msgCode, data } = (await http.post<loginData>('/authentication-server/authorization/login', { data: { code, appId, dto } })).data
  if (+msgCode !== 200) {
    uni.showToast({ title: 'login初始化失败', icon: 'none' })
    return 'get token fail'
  }
  token = data.token
  // #endif

  // #ifdef H5
  // TODO: H5登录
  // #endif

  // #ifdef APP-PLUS
  // TODO: APP登录
  uni.navigateTo({
    url: '/pages/demo/pageA',
  })
  // #endif

  return token

}

const wrapper = Lock.createLockWrapper(lock)

export const getToken = () => wrapper(login)
